<template>
  <div style="background-color: #f0f2f5; padding: 0px;">
    <PageHeader
      :breadcrumb="breadcrumb"
      style="background-color: white; padding: 24px; margin-bottom: 16px;"
    />
    <div style="background-color: white; padding: 24px; padding-top: 0px;">
    <div id="operationButton">
      <a-button
        v-if="canAddAlloyPhaseDiagram"
        size="large"
        type="primary"
        @click="onAddButtonClick"
      >
        添加
      </a-button>
        &nbsp;
        <a-button
            size="large"
            type="primary"
            @click="onRefresh"
        >
          刷新
        </a-button>
      <a-modal
        v-model:visible="addOrEditDialogVisible"
        :title="addOrEditDialogTitle"
        :width="600"
        :keyboard="false"
        :maskClosable="false"
        :footer="null"
        :destroyOnClose="true"
        centered
      >
        <AddOrEditAlloyPhaseDiagram
          :url="editUrl"
          @operate-success="onAddOrEditSuccess"
          @operate-failed="closeAddOrEditDialog"
        />
      </a-modal>
    </div>
    <a-table
      :loading="loading"
      :columns="columns"
      :data-source="data"
      :pagination="{ pageSize: 10 }"
      :scroll="{ x: 240 }"
    >
      <template
        v-if="canEditAlloyPhaseDiagram || canDeleteAlloyPhaseDiagram"
        #operation="{ record }"
      >
        <TableOperation
          :canEdit="canEditAlloyPhaseDiagram"
          :canDelete="canDeleteAlloyPhaseDiagram"
          @edit="onEdit(record.key)"
          @delete="onDelete(record.key)"
        />
        </template>
        <template #filterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
          <div style="padding: 8px">
            <a-input
                :ref="c => (searchInput = c)"
                :placeholder="`查询 ${column.title}`"
                :value="selectedKeys[0]"
                style="width: 188px; margin-bottom: 8px; display: block;"
                @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
                @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
            />
            <a-button
                type="primary"
                size="small"
                style="width: 90px; margin-right: 8px"
                @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
            >
              <template>
                <SearchOutlined/>
              </template>
              查询
            </a-button>
            <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
              重置
            </a-button>
          </div>
        </template>
        <template #filterIcon="filtered" >
          <search-outlined :style="{ color: filtered ? '#108ee9' : undefined }"/>
        </template>
        <template #customRender="{ text, column }">
              <span v-if="searchText && searchedColumn === column.dataIndex">
                <template
                    v-for="(fragment, i) in text
                    .toString()
                    .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
                >
                  <mark
                      v-if="fragment.toLowerCase() === searchText.toLowerCase()"
                      :key="i"
                      class="highlight"
                  >
                    {{ fragment }}
                  </mark>
                  <template v-else>{{ fragment }}</template>
                </template>
              </span>
          <template v-else>
            {{ text }}
          </template>
      </template>
    </a-table>
    </div>
  </div>
</template>
<script>

import PageHeader from '../Common/PageHeader'
import AddOrEditAlloyPhaseDiagram from './AddOrEditAlloyPhaseDiagram'
import TableOperation from '../Common/TableOperation'
import { message } from 'ant-design-vue'
import {SearchOutlined} from '@ant-design/icons-vue'

const operationColumn = {
  title: '操作',
  dataIndex: 'operation',
  slots: { customRender: 'operation' },
  width: 150,
}

export default {
  name: 'AlloyPhaseDiagram',
  emits: ['add'],
  components: {
    PageHeader,
    AddOrEditAlloyPhaseDiagram,
    TableOperation,
    SearchOutlined,
  },
  data() {
    const refreshInterval = 100
    return {
      breadcrumb: [
        { key: 1, title: '材料文件' },
        { key: 2, title: '合金' },
      ],
      data: [],
      loading: false,
      addOrEditDialogVisible: false,
      addOrEditDialogTitle: '',
      editUrl: '',
      canAddAlloyPhaseDiagram: false,
      canEditAlloyPhaseDiagram: false,
      canDeleteAlloyPhaseDiagram: false,
      columns: [],
      searchText: '',
      searchInput: null,
      searchedColumn: '',
      refreshInterval,
    }
  },
  mounted() {
    this.columns = this.getDataColumns()
    this.processPermission()
    this.fetch()
  },
  methods: {
    getDataColumns() {
      return [
         {
            title: '合金名称',
            dataIndex: 'alloy_name',
            width: 150,
            key: 'alloy_name',
            align: 'center',
            slots: {
              filterIcon: 'filterIcon',
              filterDropdown: 'filterDropdown',
              customRender: 'customRender',
            },

            onFilter: (value, record) =>
                record.name
                    .toString()
                    .toLowerCase()
                    .includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: visible => {
              if (visible) {
                setTimeout(() => {
                  // console.log(this.searchInput);
                  this.searchInput.focus();
                }, 0);
              }
            },
          },
          {
            title: '合金代码',
            dataIndex: 'alloy_code',
            width: 150,
            key: 'alloy_code',
            align: 'center',
            slots: {
              filterIcon: 'filterIcon',
              filterDropdown: 'filterDropdown',
              customRender: 'customRender',
            },

            onFilter: (value, record) =>
                record.name
                    .toString()
                    .toLowerCase()
                    .includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: visible => {
              if (visible) {
                setTimeout(() => {
                  // console.log(this.searchInput);
                  this.searchInput.focus();
                }, 0);
              }
            },
          },
          {
            title: '合金相图',
            dataIndex: 'alloy_phase_diagram',
            key: 'alloy_phase_diagram',
            align: 'center',
            width: 150,
            slots: {
              filterIcon: 'filterIcon',
              filterDropdown: 'filterDropdown',
              customRender: 'customRender',
            },

            onFilter: (value, record) =>
                record.name
                    .toString()
                    .toLowerCase()
                    .includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: visible => {
              if (visible) {
                setTimeout(() => {
                  // console.log(this.searchInput);
                  this.searchInput.focus();
                }, 0);
              }
            },
          },
      ]
    },
    // 处理权限
    processPermission() {
      this.axios
        .get(
          '/has_permission?permission=attachment_management.add_alloy'
        )
        .then((res) => {
          this.canAddAlloyPhaseDiagram = res.data.result
        })
        .catch((error) => {
          console.log('Error', error.message)
        })
      this.axios
        .get(
          '/has_permission?permission=attachment_management.change_alloy'
        )
        .then((res) => {
          this.canEditAlloyPhaseDiagram = res.data.result
          let last = this.columns.length
          if (
            this.columns[last - 1].dataIndex !== 'operation' &&
            this.canEditAlloyPhaseDiagram
          ) {
            this.columns.push(operationColumn)
          }
        })
        .catch((error) => {
          console.log('Error', error.message)
        })
      this.axios
        .get(
          '/has_permission?permission=attachment_management.delete_alloy'
        )
        .then((res) => {
          this.canDeleteAlloyPhaseDiagram = res.data.result
          let last = this.columns.length
          if (
            this.columns[last - 1].dataIndex !== 'operation' &&
            this.canDeleteAlloyPhaseDiagram
          ) {
            this.columns.push(operationColumn)
          }
        })
        .catch((error) => {
          console.log('Error', error.message)
        })
    },
    // 从后端获取数据
    fetch() {
      this.loading = true
      let updatedData = []
      this.axios
        .get('/attachment_management/alloy_phase_diagram/')
        .then((res) => {
          const data = res.data
          for (let i = 0; i < data.length; ++i) {
            updatedData.push({
              key: data[i].url,
              alloy_name: data[i].alloy_name,
              alloy_code: data[i].alloy_code,
              alloy_phase_diagram: data[i].alloy_phase_diagram_filename,
            })
          }
          setTimeout(() => {
            this.data = updatedData
            this.loading = false
          }, this.refreshInterval)
          // this.loading = false
          // console.log('chemical:', res)
        })
        .catch((error) => {
          setTimeout(() => {
            this.loading = false
          }, this.refreshInterval)
          console.log('Error', error.message)
        })
    },
    onAddButtonClick() {
      this.addOrEditDialogTitle = '添加合金相图'
      this.editUrl = ''
      this.addOrEditDialogVisible = true
      // this.$emit('add')
    },
    onAddOrEditSuccess() {
      this.closeAddOrEditDialog()
      this.fetch()
    },
    closeAddOrEditDialog() {
      this.addOrEditDialogVisible = false
      this.fetch()
    },
    onEdit(key) {
      this.addOrEditDialogTitle = '编辑合金相图'
      // console.log(key)
      this.editUrl = key
      this.addOrEditDialogVisible = true
    },
    onDelete(key) {
      // console.log('hello', key)
      message.loading({ content: '删除中...', key })
      const data = [...this.data]
      this.axios
        .delete(key)
        .then(() => {
          setTimeout(() => {
            message.success({ content: '删除成功！', key, duration: 2 })
            this.data = data.filter((item) => item.key !== key)
          }, 1000)
        })
        .catch((error) => {
          setTimeout(() => {
            message.error({ content: '删除失败！', key, duration: 2 })
          }, 1000)
          console.log('Error', error.message)
        })
    },
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm();
      // console.log(selectedKeys[0]);
      this.searchText = selectedKeys[0];
      this.searchedColumn = dataIndex;
      // this.$forceUpdate();
    },

    handleReset(clearFilters) {
      clearFilters();
      this.searchText = '';
    },
    onRefresh() {
      this.fetch()
    },
  },
}
</script>

<style>
#operationButton {
  text-align: right;
  padding: 20px;
}
</style>
